package com.zhang.servicedriveruser.service.impl;

import com.zhang.internalcommon.dto.Car;
import com.zhang.internalcommon.dto.ResponseResult;
import com.zhang.internalcommon.response.TerminalResponse;
import com.zhang.internalcommon.response.TrackResponse;
import com.zhang.servicedriveruser.mapper.CarMapper;
import com.zhang.servicedriveruser.remote.ServiceMapClient;
import com.zhang.servicedriveruser.service.ICarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张开琦
 * @since 2025-04-12
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {
	@Autowired
	private CarMapper carMapper;

	@Autowired
	private ServiceMapClient serviceMapClient;

	@Override
	public ResponseResult addCar(Car car) {
		LocalDateTime now = LocalDateTime.now();
		car.setGmtCreate(now);
		car.setGmtModified(now);
		carMapper.insert(car);

		// 获得此车辆的tid
		String vehicleNo = car.getVehicleNo();
		ResponseResult<TerminalResponse> responseResult = serviceMapClient.addTerminal(vehicleNo,car.getId()+"");
		String tid = responseResult.getData().getTid();
		car.setTid(tid);

		// 获得此车辆的轨迹id trid
		ResponseResult<TrackResponse> trackResponseResponseResult = serviceMapClient.addTrack(tid);
		String trid = trackResponseResponseResult.getData().getTrid();
		String trname = trackResponseResponseResult.getData().getTrname();
		car.setTrid(trid);
		car.setTrname(trname);

		carMapper.updateById(car);

		return ResponseResult.success();
	}

	@Override
	public ResponseResult<Car> getCarById(Long id) {
		HashMap<String, Object> map = new HashMap<>();
		map.put("id", id);

		List<Car> cars = carMapper.selectByMap(map);
		return ResponseResult.success(cars.get(0));
	}
}
